package boddaert.philippe.cashGame.site.deuxfoismoincher;

import java.io.IOException;
import java.util.List;

import org.apache.log4j.Logger;

import au.id.jericho.lib.html.Element;
import au.id.jericho.lib.html.Source;
import boddaert.philippe.cashGame.net.DefaultWebPageGetterFactory;
import boddaert.philippe.cashGame.net.Net;
import boddaert.philippe.cashGame.net.WebPageGetterFactory;
import boddaert.philippe.cashGame.site.ParsedSite;
import boddaert.philippe.cashGame.site.Site;
import boddaert.philippe.cashGame.site.SiteRubrique;
import boddaert.philippe.cashGame.site.WebPage;

public class WebSiteGetter {

	private final static Site siteDefinition = new DeuxFoisMoinsCherPointCom();
	private final static Logger logger = Logger.getLogger(WebSiteGetter.class);

	public static int getNumberOfPageToLoad(String urlSite) throws IOException {
		WebPage webPage = DefaultWebPageGetterFactory.get().get(urlSite);
		return parseNumberOfPage(webPage.getContent());
	}

	private static int parseNumberOfPage(String content) {
		Source source = new Source(content);

		List<Element> findAllElements = source.findAllElements("span");
		for (Element element : findAllElements) {
			if ("pdts_entete_total".equals(element.getAttributeValue("class"))) {
				logger.info("parse the number of pages : "
						+ element.getContent().toString());
				String[] split = element.getContent().toString().split(" ");
				int totalNumberOfGame = Integer.parseInt(split[0].trim());
				return (int) Math.ceil(totalNumberOfGame / 20.0);
			}
		}
		return -1;
	}

	public static ParsedSite getSite() throws Exception {
		List<SiteRubrique> rubrique = siteDefinition.getRubriques();
		ParsedSite site = new ParsedSite();
		site.setName("2xmoinscher");
		int numberOfPageRubrique = 0;
		WebPageParser webPageParser = new WebPageParser();
		for (SiteRubrique siteRubrique : rubrique) {

			String url = siteDefinition.getUrl(siteRubrique.getId());
			numberOfPageRubrique = getNumberOfPageToLoad(url);
			for (int i = 1; i <= numberOfPageRubrique; i++) {
				WebPage page = getPage(siteDefinition.getUrl(siteRubrique
						.getId(), i));
				if (page != null)
					site.addPage(webPageParser.parse(page));
			}
		}
		return site;
	}

	private static WebPage getPage(String url) {

		try {
			return DefaultWebPageGetterFactory.get().get(url);
		} catch (IOException e) {
			System.out.println("Can't retrieve url : " + url);
		}
		return null;
	}

}
